#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
阿里宝宝电商平台 - Web API服务器（简化版）
提供RESTful API接口支持前端应用
"""

from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
import json
import os
from datetime import datetime
import hashlib
import uuid
import threading
import time
import traceback

# 导入物流计算模块
try:
    from logistics_calculator import (
        calculate_shipping_fee_from_addresses,
        calculate_estimated_delivery_time,
        DEFAULT_WAREHOUSE_ADDRESS
    )
    LOGISTICS_AVAILABLE = True
except ImportError as e:
    print(f"警告：物流计算模块导入失败: {e}")
    LOGISTICS_AVAILABLE = False
    DEFAULT_WAREHOUSE_ADDRESS = "北京市朝阳区三里屯街道工体北路8号院"

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 数据文件路径（使用相对路径，基于当前文件位置）
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
REAL_PRODUCTS_FILE = os.path.join(BASE_DIR, 'ali_bao_bao', 'data', '商品数据集.json')
PRODUCT_DESCRIPTIONS_FILE = os.path.join(os.path.dirname(__file__), 'product_descriptions.json')

def load_product_descriptions():
    """加载商品描述映射文件"""
    try:
        if os.path.exists(PRODUCT_DESCRIPTIONS_FILE):
            with open(PRODUCT_DESCRIPTIONS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载商品描述文件失败: {e}")
        return {}

def save_product_descriptions(descriptions):
    """保存商品描述映射文件"""
    try:
        with open(PRODUCT_DESCRIPTIONS_FILE, 'w', encoding='utf-8') as f:
            json.dump(descriptions, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存商品描述文件失败: {e}")
        return False

def get_product_images(product_id, product_name):
    """获取商品图片列表"""
    images = []
    images_dir = os.path.join(os.path.dirname(__file__), 'images', 'products')
    
    # 支持的图片格式（按优先级）
    supported_formats = ['.jpg', '.jpeg', '.png', '.webp', '.gif']
    
    # 检查主图是否存在（支持多种格式）
    main_image_found = False
    for ext in supported_formats:
        main_image = f"{product_id}{ext}"
        main_image_path = os.path.join(images_dir, main_image)
        
        if os.path.exists(main_image_path):
            images.append(f"images/products/{main_image}")
            main_image_found = True
            break
    
    if not main_image_found:
        # 如果本地图片不存在，使用占位符
        images.append(f"https://via.placeholder.com/600x400?text={product_name}")
    
    # 检查多图（支持多种格式）
    for i in range(2, 6):  # 检查2-5张额外图片
        extra_image_found = False
        for ext in supported_formats:
            extra_image = f"{product_id}_{i}{ext}"
            extra_image_path = os.path.join(images_dir, extra_image)
            
            if os.path.exists(extra_image_path):
                images.append(f"images/products/{extra_image}")
                extra_image_found = True
                break
        
        if not extra_image_found:
            # 如果本地图片不存在，使用占位符
            images.append(f"https://via.placeholder.com/600x400?text={product_name}细节{i-1}")
    
    return images

# 加载商品描述
PRODUCT_DESCRIPTIONS = load_product_descriptions()

# 加载真实商品数据
def load_real_products():
    """加载真实商品数据"""
    try:
        # 尝试使用正确的路径
        data_file = REAL_PRODUCTS_FILE
        
        # 如果文件不存在，尝试其他可能的位置
        if not os.path.exists(data_file):
            # 尝试当前项目目录
            alt_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data', '商品数据集.json')
            if os.path.exists(alt_path):
                data_file = alt_path
            else:
                raise FileNotFoundError(f"找不到商品数据文件。尝试的路径: {REAL_PRODUCTS_FILE}, {alt_path}")
        
        with open(data_file, 'r', encoding='utf-8') as f:
            raw_products = json.load(f)
        
        # 加载商品描述映射
        descriptions = load_product_descriptions()
        
        # 转换数据格式
        products = []
        for i, product in enumerate(raw_products):
            # 生成商品ID
            product_id = product.get('ID', f'PROD{i+1:03d}')
            
            # 优先使用保存的描述，如果没有则使用默认描述
            if product_id in descriptions:
                description = descriptions[product_id]
            else:
                # 如果没有自定义描述，使用默认描述
                description = f"优质{product.get('Name', '商品')}，产地{product.get('Province', '未知')}"
            
            # 转换数据格式
            converted_product = {
                'id': product_id,
                'name': product.get('Name', '未知商品'),
                'price': float(product.get('Prize（yuan)', 0)),
                'category': product.get('Kind', 'Food'),
                'location': product.get('Province', '未知产地'),
                'merchant_id': f'SELLER{product.get("ProvinceID", 1):03d}',
                'description': description,
                'image': f"https://via.placeholder.com/300x200?text={product.get('Name', '商品')}",
                'average_rating': round(4.0 + (i % 10) * 0.1, 1),  # 4.0-4.9的评分
                'review_count': 50 + (i % 200)  # 50-249的评价数
            }
            products.append(converted_product)
        
        print(f"成功加载 {len(products)} 个真实商品")
        print(f"成功加载 {len(descriptions)} 个自定义商品描述")
        return products
        
    except Exception as e:
        print(f"加载真实商品数据失败: {e}")
        print(f"尝试的文件路径: {REAL_PRODUCTS_FILE}")
        traceback.print_exc()
        # 如果加载失败，返回模拟数据
        print("使用模拟数据作为备选")
        return [
            {
                'id': 'PROD001',
                'name': '优质苹果',
                'price': 25.00,
                'category': 'Food',
                'location': '山东烟台',
                'merchant_id': 'SELLER001',
                'description': '新鲜优质苹果，口感香甜，营养丰富',
                'image': 'https://via.placeholder.com/300x200?text=苹果',
                'average_rating': 4.5,
                'review_count': 128
            }
        ]

# 加载商品数据
REAL_PRODUCTS = load_real_products()

# 用户购物车数据存储
USER_CARTS = {}

# 评价数据文件
REVIEWS_FILE = os.path.join(os.path.dirname(__file__), 'reviews.json')

def load_reviews():
    """加载评价数据"""
    try:
        if os.path.exists(REVIEWS_FILE):
            with open(REVIEWS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return []
    except Exception as e:
        print(f"加载评价数据失败: {e}")
        return []

def save_reviews(reviews):
    """保存评价数据"""
    try:
        with open(REVIEWS_FILE, 'w', encoding='utf-8') as f:
            json.dump(reviews, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存评价数据失败: {e}")
        return False

# 加载评价数据
REVIEWS = load_reviews()

# 卖家商品和店铺数据文件路径
SELLER_PRODUCTS_FILE = os.path.join(os.path.dirname(__file__), 'seller_products.json')
SELLER_SHOPS_FILE = os.path.join(os.path.dirname(__file__), 'seller_shops.json')
USER_CARTS_FILE = os.path.join(os.path.dirname(__file__), 'user_carts.json')
USER_ORDERS_FILE = os.path.join(os.path.dirname(__file__), 'user_orders.json')

def load_seller_products():
    """加载卖家商品数据"""
    try:
        if os.path.exists(SELLER_PRODUCTS_FILE):
            with open(SELLER_PRODUCTS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载卖家商品数据失败: {e}")
        return {}

def save_seller_products(products):
    """保存卖家商品数据"""
    try:
        with open(SELLER_PRODUCTS_FILE, 'w', encoding='utf-8') as f:
            json.dump(products, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存卖家商品数据失败: {e}")
        return False

def load_seller_shops():
    """加载卖家店铺数据"""
    try:
        if os.path.exists(SELLER_SHOPS_FILE):
            with open(SELLER_SHOPS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载卖家店铺数据失败: {e}")
        return {}

def save_seller_shops(shops):
    """保存卖家店铺数据"""
    try:
        with open(SELLER_SHOPS_FILE, 'w', encoding='utf-8') as f:
            json.dump(shops, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存卖家店铺数据失败: {e}")
        return False

def load_user_carts():
    """加载用户购物车数据"""
    try:
        if os.path.exists(USER_CARTS_FILE):
            with open(USER_CARTS_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载用户购物车数据失败: {e}")
        return {}

def save_user_carts(carts):
    """保存用户购物车数据"""
    try:
        with open(USER_CARTS_FILE, 'w', encoding='utf-8') as f:
            json.dump(carts, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存用户购物车数据失败: {e}")
        return False

def load_user_orders():
    """加载用户订单数据"""
    try:
        if os.path.exists(USER_ORDERS_FILE):
            with open(USER_ORDERS_FILE, 'r', encoding='utf-8') as f:
                orders = json.load(f)
            # 为已存在的订单补全created_at_timestamp字段
            updated = False
            for username, user_orders in orders.items():
                for order in user_orders:
                    if 'created_at_timestamp' not in order:
                        try:
                            created_at_str = order.get('created_at', '')
                            if created_at_str:
                                created_at_timestamp = datetime.fromisoformat(created_at_str).timestamp()
                                order['created_at_timestamp'] = created_at_timestamp
                                updated = True
                        except Exception as e:
                            print(f"订单 {order.get('order_number')} 时间戳解析失败: {e}")
            # 如果有更新，保存补全后的数据
            if updated:
                save_user_orders(orders)
            return orders
        return {}
    except Exception as e:
        print(f"加载用户订单数据失败: {e}")
        return {}

def save_user_orders(orders=None):
    """保存用户订单数据"""
    try:
        # 如果没有传入参数，使用全局的USER_ORDERS
        orders_to_save = orders if orders is not None else USER_ORDERS
        with open(USER_ORDERS_FILE, 'w', encoding='utf-8') as f:
            json.dump(orders_to_save, f, ensure_ascii=False, indent=2)
        print(f"[保存订单] 订单数据已保存到文件: {USER_ORDERS_FILE}")
        return True
    except Exception as e:
        print(f"保存用户订单数据失败: {e}")
        traceback.print_exc()
        return False

# 加载用户数据
USER_CARTS = load_user_carts()  # 加载用户购物车数据
USER_ORDERS = load_user_orders()  # 加载用户订单数据

# 加载卖家数据
SELLER_PRODUCTS = load_seller_products()  # 加载卖家商品数据
SELLER_SHOPS = load_seller_shops()  # 加载卖家店铺数据

# 订单状态自动更新函数
def update_order_status():
    """自动更新订单状态"""
    while True:
        try:
            current_time = datetime.now().timestamp()
            updated = False
            
            # 遍历所有用户的订单
            for username, orders in USER_ORDERS.items():
                for order in orders:
                    order_status = order.get('status', 'Processing')
                    
                    # 跳过已送达的订单
                    if order_status == 'Delivered':
                        continue
                    
                    # 获取订单创建时间戳
                    created_at_timestamp = order.get('created_at_timestamp')
                    if not created_at_timestamp:
                        # 如果没有时间戳，从created_at解析
                        try:
                            created_at_str = order.get('created_at', '')
                            created_at_timestamp = datetime.fromisoformat(created_at_str).timestamp()
                            order['created_at_timestamp'] = created_at_timestamp
                        except:
                            continue
                    
                    # 计算订单创建后的时间（秒）
                    elapsed_seconds = current_time - created_at_timestamp
                    elapsed_minutes = elapsed_seconds / 60
                    
                    # 获取预计送达时间戳
                    estimated_delivery_timestamp = order.get('estimated_delivery', 0)
                    if not estimated_delivery_timestamp:
                        continue
                    
                    # 计算预计配送时间（天）
                    delivery_time_seconds = estimated_delivery_timestamp - created_at_timestamp
                    delivery_time_days = delivery_time_seconds / (24 * 3600)
                    
                    # 计算状态更新时间（分钟）
                    # 1分钟后改为"已发货"
                    shipped_time_minutes = 1
                    # 根据配送时间计算"已送达"时间
                    # 如果配送时间 <= 1天，等待1分钟后改为"已送达"
                    # 如果配送时间 > 1天，每多一天增加1分钟
                    if delivery_time_days <= 1:
                        delivered_time_minutes = 1 + 1  # 1分钟发货 + 1分钟送达 = 2分钟
                    else:
                        # 向上取整天数，例如1.1天 = 2天
                        delivery_days_ceil = int(delivery_time_days) + (1 if delivery_time_days % 1 > 0 else 0)
                        delivered_time_minutes = shipped_time_minutes + delivery_days_ceil
                    
                    # 更新订单状态
                    if order_status == 'Processing' and elapsed_minutes >= shipped_time_minutes:
                        order['status'] = 'Shipped'
                        order['shipped_at'] = datetime.now().isoformat()
                        updated = True
                        print(f"订单 {order.get('order_number')} 状态更新为: 已发货")
                    
                    elif order_status == 'Shipped' and elapsed_minutes >= delivered_time_minutes:
                        order['status'] = 'Delivered'
                        order['delivered_at'] = datetime.now().isoformat()
                        updated = True
                        print(f"订单 {order.get('order_number')} 状态更新为: 已送达")
            
            # 如果有更新，保存到文件
            if updated:
                save_user_orders(USER_ORDERS)
            
            # 每10秒检查一次
            time.sleep(10)
            
        except Exception as e:
            print(f"订单状态更新错误: {e}")
            time.sleep(10)

# 启动订单状态自动更新线程
order_status_thread = threading.Thread(target=update_order_status, daemon=True)
order_status_thread.start()
print("订单状态自动更新线程已启动")

# 用户数据管理
USER_DATA_FILE = os.path.join(os.path.dirname(__file__), 'users.json')

def load_users():
    """加载用户数据"""
    try:
        if os.path.exists(USER_DATA_FILE):
            with open(USER_DATA_FILE, 'r', encoding='utf-8') as f:
                return json.load(f)
        return {}
    except Exception as e:
        print(f"加载用户数据失败: {e}")
        return {}

def save_users(users):
    """保存用户数据"""
    try:
        with open(USER_DATA_FILE, 'w', encoding='utf-8') as f:
            json.dump(users, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存用户数据失败: {e}")
        return False

def hash_password(password):
    """密码哈希"""
    return hashlib.sha256(password.encode()).hexdigest()

def verify_password(password, hashed):
    """验证密码"""
    return hash_password(password) == hashed

# 加载用户数据
USERS = load_users()

# 如果没有用户数据或管理员不存在，创建管理员账户
if not USERS:
    USERS = {}

# 确保管理员账户存在
admin_username = 'Mike.Chen'
if admin_username not in USERS or USERS[admin_username].get('user_type') != 'Admin':
    USERS[admin_username] = {
        'user_id': 'ADMIN001',
        'username': admin_username,
        'password': hash_password('Chen@123'),
        'email': 'mike.chen@admin.com',
        'phone': '138-0000-0001',
        'user_type': 'Admin',
            'created_at': datetime.now().isoformat()
    }
    save_users(USERS)
    print(f"创建管理员账户: {admin_username} / Chen@123")

@app.route('/')
def index():
    """首页 - 返回静态HTML文件"""
    return send_from_directory('.', 'index.html')

# API路由定义（必须在静态文件路由之前）
@app.route('/api/auth/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not username or not password:
            return jsonify({'success': False, 'error': '用户名和密码不能为空'}), 400
        
        # 查找用户
        if username in USERS:
            user = USERS[username]
            if verify_password(password, user['password']):
                # 生成token
                token = hashlib.md5(f"{username}{datetime.now()}".encode()).hexdigest()
                
                # 返回用户信息（不包含密码）
                user_data = {
                    'user_id': user['user_id'],
                    'username': user['username'],
                    'email': user['email'],
                    'phone': user['phone'],
                    'user_type': user['user_type'],
                    'token': token
                }
                
                return jsonify({
                    'success': True,
                    'data': user_data
                })
            else:
                return jsonify({'success': False, 'error': '密码错误'}), 401
        else:
            return jsonify({'success': False, 'error': '用户不存在'}), 401
            
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/auth/register', methods=['POST'])
def register():
    """用户注册"""
    global SELLER_SHOPS, SELLER_PRODUCTS  # 声明使用全局变量
    
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        email = data.get('email')
        phone = data.get('phone')
        user_type = data.get('userType', 'Customer')
        
        if not all([username, password, email, phone]):
            return jsonify({'success': False, 'error': '所有字段都是必填的'}), 400
        
        # 检查用户名是否已存在
        if username in USERS:
            return jsonify({'success': False, 'error': '用户名已存在'}), 400
        
        # 生成用户ID
        user_id = f"USER{len(USERS) + 1:03d}"
        
        # 创建新用户
        new_user = {
            'user_id': user_id,
            'username': username,
            'password': hash_password(password),
            'email': email,
            'phone': phone,
            'user_type': user_type,
            'created_at': datetime.now().isoformat()
        }
        
        # 保存用户
        USERS[username] = new_user
        if save_users(USERS):
            # 如果是卖家，创建店铺信息
            if user_type == 'Seller':
                try:
                    shop_name = data.get('shopName', f"{username}的店铺")
                    # 确保SELLER_SHOPS和SELLER_PRODUCTS已初始化
                    if SELLER_SHOPS is None:
                        SELLER_SHOPS = load_seller_shops()
                    if SELLER_PRODUCTS is None:
                        SELLER_PRODUCTS = load_seller_products()
                    
                    shop_id = f"SHOP{len(SELLER_SHOPS) + 1:03d}"
                    
                    shop_info = {
                        'shop_id': shop_id,
                        'owner_username': username,
                        'name': shop_name,
                        'description': f"欢迎来到{shop_name}，优质商品，诚信经营！",
                        'logo': f"https://via.placeholder.com/100x100?text={shop_name[:2]}",
                        'address': '待完善',
                        'phone': phone,
                        'email': email,
                        'created_at': datetime.now().isoformat(),
                        'status': 'active'
                    }
                    
                    SELLER_SHOPS[username] = shop_info
                    if not save_seller_shops(SELLER_SHOPS):
                        print(f"警告：保存卖家店铺信息失败: {username}")
                    
                    # 初始化卖家的商品列表
                    SELLER_PRODUCTS[username] = []
                    if not save_seller_products(SELLER_PRODUCTS):
                        print(f"警告：保存卖家商品列表失败: {username}")
                    
                    print(f"卖家注册成功: {username}, 店铺ID: {shop_id}")
                except Exception as shop_error:
                    print(f"创建卖家店铺信息时出错: {shop_error}")
                    traceback.print_exc()
                    # 即使店铺创建失败，也继续完成用户注册
                    pass
            
            # 生成token
            token = hashlib.md5(f"{username}{datetime.now()}".encode()).hexdigest()
            
            # 返回用户信息（不包含密码）
            user_data = {
                'user_id': user_id,
                'username': username,
                'email': email,
                'phone': phone,
                'user_type': user_type,
                'token': token
            }
            
            return jsonify({
                'success': True,
                'data': user_data
            })
        else:
            return jsonify({'success': False, 'error': '注册失败，请稍后重试'}), 500
        
    except Exception as e:
        print(f"注册失败: {e}")
        traceback.print_exc()
        return jsonify({'success': False, 'error': f'注册失败: {str(e)}'}), 500

@app.route('/api/auth/logout', methods=['POST'])
def logout():
    """用户登出"""
    try:
        # 登出接口，简单返回成功
        return jsonify({
            'success': True,
            'data': {
                'message': '登出成功'
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products', methods=['GET'])
def get_products():
    """获取商品列表"""
    try:
        page = int(request.args.get('page', 1))
        limit = int(request.args.get('limit', 12))
        category = request.args.get('category')
        
        # 按分类过滤
        products = REAL_PRODUCTS
        if category:
            products = [p for p in products if p['category'] == category]
        
        # 分页
        start = (page - 1) * limit
        end = start + limit
        page_products = products[start:end]
        
        # 为每个商品添加图片信息
        for product in page_products:
            images = get_product_images(product['id'], product['name'])
            product['image'] = images[0] if images else f"https://via.placeholder.com/400x300?text={product['name']}"
            product['images'] = images
        
        return jsonify({
            'success': True,
            'data': {
                'products': page_products,
                'total': len(products),
                'page': page,
                'limit': limit,
                'has_more': end < len(products)
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products/<product_id>/description', methods=['PUT'])
def update_product_description(product_id):
    """更新商品描述（只更新description字段）"""
    try:
        print(f"[更新商品描述API] 收到请求，商品ID: {product_id}")
        data = request.get_json()
        description = data.get('description', '')
        
        if not description:
            print("[更新商品描述API] 错误: 商品描述为空")
            return jsonify({'success': False, 'error': '商品描述不能为空'}), 400
        
        # 在REAL_PRODUCTS中查找商品
        product_found = False
        for product in REAL_PRODUCTS:
            if product.get('id') == product_id:
                # 更新内存中的描述
                product['description'] = description
                product_found = True
                print(f"[更新商品描述API] 成功更新内存中商品 {product_id} 的描述")
                break
        
        if not product_found:
            print(f"[更新商品描述API] 错误: 商品 {product_id} 不存在")
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        # 保存描述到文件（持久化）
        global PRODUCT_DESCRIPTIONS
        PRODUCT_DESCRIPTIONS[product_id] = description
        if save_product_descriptions(PRODUCT_DESCRIPTIONS):
            print(f"[更新商品描述API] 成功保存商品 {product_id} 的描述到文件")
        else:
            print(f"[更新商品描述API] 警告: 保存商品 {product_id} 的描述到文件失败，但内存已更新")
        
        return jsonify({
            'success': True,
            'data': {
                'id': product_id,
                'description': description
            }
        })
        
    except Exception as e:
        print(f"[更新商品描述API] 错误: {e}")
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products/<product_id>/sales', methods=['GET'])
def get_product_sales(product_id):
    """获取商品购买量（从订单中统计）"""
    try:
        print(f"[商品购买量API] 收到请求，商品ID: {product_id}")
        total_quantity = 0
        
        # 遍历所有用户的订单
        for username, orders in USER_ORDERS.items():
            for order in orders:
                items = order.get('items', [])
                for item in items:
                    # 检查商品ID是否匹配（支持多种字段名）
                    item_product_id = item.get('productId') or item.get('product_id') or item.get('id')
                    if item_product_id == product_id:
                        quantity = item.get('quantity', 1)
                        total_quantity += quantity
        
        print(f"[商品购买量API] 商品 {product_id} 的购买量: {total_quantity}")
        return jsonify({
            'success': True,
            'data': {
                'product_id': product_id,
                'total_quantity': total_quantity
            }
        })
        
    except Exception as e:
        print(f"[商品购买量API] 错误: {e}")
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/purchase-statistics', methods=['GET'])
def get_purchase_statistics():
    """获取商品分类购买统计（用于饼状图）"""
    try:
        print(f"[购买统计API] 收到请求")
        
        # 统计每个商品分类的购买量
        category_stats = {}
        
        # 遍历所有用户的订单
        for username, orders in USER_ORDERS.items():
            for order in orders:
                items = order.get('items', [])
                for item in items:
                    # 获取商品ID
                    product_id = item.get('productId') or item.get('product_id') or item.get('id')
                    quantity = item.get('quantity', 1)
                    
                    # 查找商品的分类
                    product = next((p for p in REAL_PRODUCTS if p.get('id') == product_id), None)
                    if product:
                        category = product.get('category', '其他')
                        
                        # 中文分类名称映射
                        category_names = {
                            'Food': '食品',
                            'Clothing': '服装',
                            'Book': '图书',
                            'Electronic Products': '电子产品',
                            'Daily product': '日用品'
                        }
                        category_name = category_names.get(category, '其他')
                        
                        if category_name not in category_stats:
                            category_stats[category_name] = 0
                        category_stats[category_name] += quantity
        
        # 转换为列表格式，用于图表
        statistics = []
        for category, quantity in category_stats.items():
            statistics.append({
                'category': category,
                'quantity': quantity
            })
        
        # 按数量降序排序
        statistics.sort(key=lambda x: x['quantity'], reverse=True)
        
        print(f"[购买统计API] 统计结果: {statistics}")
        
        return jsonify({
            'success': True,
            'data': {
                'statistics': statistics,
                'total_quantity': sum(s['quantity'] for s in statistics)
            }
        })
        
    except Exception as e:
        print(f"[购买统计API] 错误: {e}")
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products/<product_id>', methods=['GET'])
def get_product_detail(product_id):
    """获取商品详情"""
    try:
        product = next((p for p in REAL_PRODUCTS if p['id'] == product_id), None)
        
        if not product:
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        # 扩展商品详情
        product_detail = {
            **product,
            'original_price': product['price'] * 1.2,
            'images': get_product_images(product['id'], product['name']),
            'specifications': {
                '产地': product['location'],
                '净重': '5kg',
                '保质期': '12个月',
                '储存方式': '阴凉干燥处',
                '包装': '真空包装'
            },
            'stock': 999
        }
        
        return jsonify({
            'success': True,
            'data': product_detail
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/products/search', methods=['POST'])
def search_products():
    """搜索商品 - 使用模糊搜索算法"""
    try:
        data = request.get_json()
        keyword = data.get('keyword', '')
        filters = data.get('filters', {})
        
        if not keyword:
            return jsonify({'success': False, 'error': '搜索关键词不能为空'}), 400
        
        # 使用模糊搜索算法
        results = fuzzy_search_products(keyword, REAL_PRODUCTS)
        
        # 应用额外过滤器
        if filters.get('category'):
            results = [p for p in results if p.get('category', '').lower() == filters['category'].lower()]
        
        if filters.get('min_price'):
            results = [p for p in results if p.get('price', 0) >= filters['min_price']]
        
        if filters.get('max_price'):
            results = [p for p in results if p.get('price', 0) <= filters['max_price']]
        
        # 为搜索结果添加图片信息
        for product in results:
            images = get_product_images(product['id'], product['name'])
            product['image'] = images[0] if images else f"https://via.placeholder.com/400x300?text={product['name']}"
            product['images'] = images
        
        return jsonify({
            'success': True,
            'data': {
                'products': results,
                'total': len(results),
                'keyword': keyword
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

def fuzzy_search_products(keyword: str, products: list) -> list:
    """高级模糊搜索商品 - 支持智能字符级模糊匹配和噪音过滤"""
    keyword = keyword.lower().strip()
    results = []
    
    # 过滤噪音字符
    noise_chars = ['子', '的', '了', '在', '是', '和', '有', '就', '与', '等', '或']
    
    # 如果搜索关键词是单个噪音字符，直接返回空结果
    if len(keyword) == 1 and keyword in noise_chars:
        return []
    
    for p in products:
        score = 0
        name_lower = p.get('name', '').lower()
        
        # 第一级：完整匹配
        if keyword in name_lower:
            if name_lower == keyword:
                score += 100  # 完全匹配
            elif name_lower.startswith(keyword):
                score += 80   # 开头匹配
            else:
                score += 50  # 包含匹配
        
        # 第二级：字符级模糊匹配
        else:
            max_consecutive_match = 0
            
            # 查找最长连续子串匹配
            for i in range(len(keyword)):
                for j in range(i + 1, len(keyword) + 1):
                    substring = keyword[i:j]
                    if substring in name_lower:
                        max_consecutive_match = max(max_consecutive_match, len(substring))
            
            # 连续子串匹配
            if max_consecutive_match >= 1:
                match_ratio = max_consecutive_match / len(keyword)
                score += int(30 * match_ratio)
                
                # 过滤噪音：如果只匹配了一个字符且是噪音字符
                if max_consecutive_match == 1 and len(keyword) == 1 and keyword in noise_chars:
                    score = 0
            else:
                # 有意义字符匹配
                meaningful_match_count = 0
                for char in keyword:
                    if char not in noise_chars and char in name_lower:
                        meaningful_match_count += 1
                
                if meaningful_match_count >= 1:
                    score += int(10 * (meaningful_match_count / len(keyword)))
        
        # 如果有匹配，添加到结果中
        if score > 0:
            results.append((p, score))
    
    # 按匹配度排序，匹配度相同时按名称排序
    sorted_results = sorted(results, key=lambda x: (-x[1], x[0].get('name', '')))
    return [p for p, _ in sorted_results]

@app.route('/api/cart', methods=['GET'])
def get_cart():
    """获取购物车"""
    try:
        # 优先从自定义请求头中获取用户名（由前端发送）
        username = request.headers.get('X-Username')
        if not username:
            # 回退：从Authorization头中提取（兼容旧逻辑）
            auth_header = request.headers.get('Authorization')
            if not auth_header:
                return jsonify({'success': False, 'error': '未登录'}), 401
            username = auth_header.replace('Bearer ', '')
        
        # 获取用户的购物车
        user_cart = USER_CARTS.get(username, [])
        
        # 计算总价
        total = sum(item['price'] * item['quantity'] for item in user_cart)
        
        return jsonify({
            'success': True,
            'data': {
                'items': user_cart,
                'total': total
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/cart/add', methods=['POST'])
def add_to_cart():
    """添加到购物车"""
    try:
        # 优先从自定义请求头中获取用户名
        username = request.headers.get('X-Username')
        if not username:
            auth_header = request.headers.get('Authorization')
            if not auth_header:
                return jsonify({'success': False, 'error': '未登录'}), 401
            username = auth_header.replace('Bearer ', '')
        
        data = request.get_json()
        product_id = data.get('productId')
        quantity = data.get('quantity', 1)
        
        if not product_id:
            return jsonify({'success': False, 'error': '商品ID不能为空'}), 400
        
        # 查找商品
        product = next((p for p in REAL_PRODUCTS if p['id'] == product_id), None)
        if not product:
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        # 获取或创建用户购物车
        if username not in USER_CARTS:
            USER_CARTS[username] = []
        
        # 检查商品是否已在购物车中
        existing_item = None
        for item in USER_CARTS[username]:
            if item['product_id'] == product_id:
                existing_item = item
                break
        
        if existing_item:
            # 更新数量
            existing_item['quantity'] += quantity
        else:
            # 添加新商品
            cart_item = {
                'product_id': product_id,
                'product_name': product['name'],
                'price': product['price'],
                'quantity': quantity,
                'selected': False,
                'image': product.get('image', ''),
                'category': product.get('category', '')
            }
            USER_CARTS[username].append(cart_item)
        
        # 保存购物车数据
        save_user_carts(USER_CARTS)
        
        return jsonify({
            'success': True,
            'data': {
                'message': '商品已添加到购物车',
                'product_id': product_id,
                'quantity': quantity
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/cart/update', methods=['POST'])
def update_cart():
    """更新购物车商品数量"""
    try:
        # 优先从自定义请求头中获取用户名
        username = request.headers.get('X-Username')
        if not username:
            auth_header = request.headers.get('Authorization')
            if not auth_header:
                return jsonify({'success': False, 'error': '未登录'}), 401
            username = auth_header.replace('Bearer ', '')
        
        data = request.get_json()
        product_id = data.get('productId')
        quantity = data.get('quantity', 1)
        
        if not product_id:
            return jsonify({'success': False, 'error': '商品ID不能为空'}), 400
        
        if username not in USER_CARTS:
            return jsonify({'success': False, 'error': '购物车为空'}), 404
        
        # 查找并更新商品
        for item in USER_CARTS[username]:
            if item['product_id'] == product_id:
                item['quantity'] = max(1, quantity)  # 最少1个
                save_user_carts(USER_CARTS)
                return jsonify({
                    'success': True,
                    'data': {
                        'message': '购物车已更新',
                        'product_id': product_id,
                        'quantity': item['quantity']
                    }
                })
        
        return jsonify({'success': False, 'error': '商品不在购物车中'}), 404
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/cart/remove', methods=['POST'])
def remove_from_cart():
    """从购物车移除商品"""
    try:
        # 优先从自定义请求头中获取用户名
        username = request.headers.get('X-Username')
        if not username:
            auth_header = request.headers.get('Authorization')
            if not auth_header:
                return jsonify({'success': False, 'error': '未登录'}), 401
            username = auth_header.replace('Bearer ', '')
        
        data = request.get_json()
        product_id = data.get('productId')
        
        if not product_id:
            return jsonify({'success': False, 'error': '商品ID不能为空'}), 400
        
        # 如果用户购物车不存在，创建空购物车
        if username not in USER_CARTS:
            USER_CARTS[username] = []
        
        # 移除商品（如果存在）
        original_count = len(USER_CARTS[username])
        USER_CARTS[username] = [item for item in USER_CARTS[username] if item['product_id'] != product_id]
        
        # 保存购物车数据
        save_user_carts(USER_CARTS)
        
        return jsonify({
            'success': True,
            'data': {
                'message': '商品已从购物车移除',
                'product_id': product_id,
                'removed': original_count > len(USER_CARTS[username])
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/cart/clear', methods=['POST'])
def clear_cart():
    """清空购物车"""
    try:
        # 从请求头获取用户token
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return jsonify({'success': False, 'error': '未登录'}), 401
        
        username = auth_header.replace('Bearer ', '')
        
        # 清空购物车
        USER_CARTS[username] = []
        save_user_carts(USER_CARTS)
        
        return jsonify({
            'success': True,
            'data': {
                'message': '购物车已清空'
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/orders', methods=['GET'])
def get_orders():
    """获取用户订单"""
    try:
        # 获取用户信息
        auth_header = request.headers.get('Authorization')
        username = request.headers.get('X-Username')
        if not username and auth_header:
            username = auth_header.replace('Bearer ', '')
        
        print(f"[获取订单] 获取到的用户名: {username}")
        print(f"[获取订单] Authorization头: {auth_header}")
        print(f"[获取订单] X-Username头: {request.headers.get('X-Username')}")
        
        if not username:
            print("[获取订单] 错误: 未获取到用户名")
            return jsonify({'success': False, 'error': '未登录或无法识别用户'}), 401
        
        # 获取用户的订单
        user_orders = USER_ORDERS.get(username, [])
        print(f"[获取订单] 用户 {username} 的订单数量: {len(user_orders)}")
        print(f"[获取订单] 所有用户订单键: {list(USER_ORDERS.keys())}")
        
        return jsonify({
            'success': True,
            'data': {
                'orders': user_orders
            }
        })
        
    except Exception as e:
        print(f"[获取订单] 异常: {str(e)}")
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/orders/<order_id>', methods=['GET'])
def get_order_detail(order_id):
    """获取订单详情"""
    try:
        # 获取用户信息
        auth_header = request.headers.get('Authorization')
        username = request.headers.get('X-Username')
        if not username and auth_header:
            username = auth_header.replace('Bearer ', '')
        
        if not username:
            return jsonify({'success': False, 'error': '未登录或无法识别用户'}), 401
        
        # 查找订单
        user_orders = USER_ORDERS.get(username, [])
        order = next((o for o in user_orders if o['order_number'] == order_id), None)
        
        if not order:
            return jsonify({'success': False, 'error': '订单不存在'}), 404
        
        return jsonify({
            'success': True,
            'data': order
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/orders/create', methods=['POST'])
def create_order():
    """创建订单"""
    try:
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['items', 'shippingAddress', 'paymentMethod']
        for field in required_fields:
            if field not in data:
                return jsonify({'success': False, 'error': f'缺少必要字段: {field}'}), 400
        
        # 生成订单号
        order_number = f"ORD{int(datetime.now().timestamp())}{uuid.uuid4().hex[:6].upper()}"
        
        # 计算总金额并获取商品产地信息
        total_amount = 0
        origin_addresses = {}  # 统计每个产地的商品数量
        processed_items = []  # 处理后的订单项（包含产地信息）
        
        for item in data['items']:
            # 优先使用订单项中已有的价格和产地信息
            item_price = item.get('price', 0)
            item_location = item.get('location', '')
            
            # 如果没有价格或产地信息，尝试从REAL_PRODUCTS中查找
            product = None
            if not item_price or not item_location:
                product = next((p for p in REAL_PRODUCTS if p['id'] == item['productId']), None)
            
            # 使用商品信息补充订单项数据
            if product:
                item_price = item_price or product.get('price', 0)
                item_location = item_location or product.get('location', '')
            
            # 计算总金额
            total_amount += item_price * item['quantity']
            
            # 获取商品产地地址（优先使用订单项中的location，再从product中获取）
            origin_address = item_location or ''
            
            # 添加到处理后的订单项（包含产地信息）
            processed_item = item.copy()
            processed_item['price'] = item_price  # 确保价格字段存在
            
            if origin_address and origin_address != '未知产地':
                processed_item['origin_address'] = origin_address
                # 统计每个产地的商品数量
                if origin_address not in origin_addresses:
                    origin_addresses[origin_address] = 0
                origin_addresses[origin_address] += item['quantity']
            
            processed_items.append(processed_item)
        
        # 确定主发货地（商品数量最多的产地）
        if origin_addresses:
            main_origin_address = max(origin_addresses.items(), key=lambda x: x[1])[0]
            origin_count = len(origin_addresses)
        else:
            # 如果没有找到产地信息，使用默认仓库地址
            main_origin_address = DEFAULT_WAREHOUSE_ADDRESS
            origin_count = 1
        
        # 计算运费（使用物流计算模块）
        shipping_address = data['shippingAddress']
        delivery_address = f"{shipping_address.get('address', '')}"
        
        # 初始化物流相关变量
        logistics_error = None
        distance_km = None
        duration_h = None
        
        # 计算多发货地附加费
        multi_origin_fee = (origin_count - 1) * 3 if origin_count > 1 else 0
        
        if LOGISTICS_AVAILABLE:
            # 使用商品的实际产地地址计算运费
            logistics_result = calculate_shipping_fee_from_addresses(
                main_origin_address,
                delivery_address,
                use_api=True
            )
            
            base_shipping_fee = logistics_result['shipping_fee']
            distance_km = logistics_result.get('distance_km')
            duration_h = logistics_result.get('duration_h')
            logistics_error = logistics_result.get('error')
            
            # 总运费 = 基础运费 + 多发货地附加费
            shipping_fee = base_shipping_fee + multi_origin_fee
            
            if logistics_error:
                print(f"物流计算警告: {logistics_error}，使用默认运费")
        else:
            # 如果没有物流模块，使用默认运费
            base_shipping_fee = 15.00
            shipping_fee = base_shipping_fee + multi_origin_fee
            logistics_error = "物流计算模块未启用"
        
        total_amount += shipping_fee
        
        # 应用折扣
        discount = data.get('discount', 0)
        if discount > 0:
            total_amount = total_amount * (1 - discount / 100)
        
        # 计算预计送达时间（基于物流信息）
        if LOGISTICS_AVAILABLE:
            estimated_delivery_timestamp = calculate_estimated_delivery_time(
                distance_km=distance_km,
                duration_h=duration_h
            )
        else:
            # 如果没有物流模块，使用默认3天
            estimated_delivery_timestamp = datetime.now().timestamp() + 3 * 24 * 3600
        
        # 获取用户信息
        auth_header = request.headers.get('Authorization')
        username = request.headers.get('X-Username')
        if not username and auth_header:
            username = auth_header.replace('Bearer ', '')
        
        print(f"[创建订单] 获取到的用户名: {username}")
        print(f"[创建订单] Authorization头: {auth_header}")
        print(f"[创建订单] X-Username头: {request.headers.get('X-Username')}")
        
        if not username:
            print("[创建订单] 错误: 未获取到用户名")
            return jsonify({'success': False, 'error': '未登录或无法识别用户'}), 401
        
        # 创建订单数据
        order_data = {
            'order_number': order_number,
            'items': processed_items,  # 使用包含产地信息的订单项
            'shipping_address': data['shippingAddress'],
            'payment_method': data['paymentMethod'],
            'total_amount': round(total_amount, 2),
            'shipping_fee': shipping_fee,
            'multi_origin_fee': multi_origin_fee,  # 多发货地附加费
            'discount': discount,
            'status': 'Processing',
            'created_at': datetime.now().isoformat(),
            'created_at_timestamp': datetime.now().timestamp(),  # 添加时间戳用于状态更新
            'estimated_delivery': estimated_delivery_timestamp,
            # 物流信息
            'logistics': {
                'distance_km': distance_km,
                'duration_h': duration_h,
                'warehouse_address': main_origin_address,  # 使用实际的主发货地地址
                'origin_addresses': list(origin_addresses.keys()),  # 所有发货地列表
                'origin_count': origin_count,  # 发货地数量
                'calculated': LOGISTICS_AVAILABLE and distance_km is not None,
                'error': logistics_error
            }
        }
        
        # 保存订单到用户订单列表
        if username not in USER_ORDERS:
            USER_ORDERS[username] = []
        
        USER_ORDERS[username].append(order_data)
        print(f"[创建订单] 保存订单前，用户 {username} 的订单数量: {len(USER_ORDERS.get(username, []))}")
        save_user_orders(USER_ORDERS)
        print(f"[创建订单] 保存订单后，用户 {username} 的订单数量: {len(USER_ORDERS.get(username, []))}")
        print(f"[创建订单] 订单号: {order_number}, 订单数据: {json.dumps(order_data, ensure_ascii=False, indent=2)}")
        
        return jsonify({
            'success': True,
            'data': order_data
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/logistics/calculate', methods=['POST'])
def calculate_logistics():
    """计算物流运费"""
    try:
        data = request.get_json()
        delivery_address = data.get('delivery_address', '')
        
        if not delivery_address:
            return jsonify({'success': False, 'error': '请提供收货地址'}), 400
        
        if LOGISTICS_AVAILABLE:
            # 使用物流计算模块计算运费
            logistics_result = calculate_shipping_fee_from_addresses(
                DEFAULT_WAREHOUSE_ADDRESS,
                delivery_address,
                use_api=True
            )
            
            return jsonify({
                'success': True,
                'data': {
                    'shipping_fee': logistics_result['shipping_fee'],
                    'distance_km': logistics_result.get('distance_km'),
                    'duration_h': logistics_result.get('duration_h'),
                    'warehouse_address': DEFAULT_WAREHOUSE_ADDRESS,
                    'delivery_address': delivery_address,
                    'calculated': logistics_result['success'],
                    'error': logistics_result.get('error')
                }
            })
        else:
            return jsonify({
                'success': False,
                'error': '物流计算模块未启用',
                'data': {
                    'shipping_fee': 15.0,
                    'distance_km': None,
                    'duration_h': None,
                    'warehouse_address': DEFAULT_WAREHOUSE_ADDRESS,
                    'delivery_address': delivery_address,
                    'calculated': False
                }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/recommendations', methods=['GET'])
def get_recommendations():
    """获取推荐商品"""
    try:
        limit = int(request.args.get('limit', 10))
        
        # 返回热门商品
        recommendations = REAL_PRODUCTS[:limit]
        
        return jsonify({
            'success': True,
            'data': {
                'products': recommendations,
                'type': 'trending'
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/reviews/<product_id>', methods=['GET'])
def get_product_reviews(product_id):
    """获取商品评价"""
    try:
        # 获取该商品的所有已审核通过的评价
        product_reviews = [r for r in REVIEWS if r.get('product_id') == product_id and r.get('is_approved', True)]
        
        # 计算平均评分（基于商品评分）
        if product_reviews:
            avg_rating = sum(r.get('product_rating', r.get('rating', 0)) for r in product_reviews) / len(product_reviews)
        else:
            avg_rating = 0.0
        
        return jsonify({
            'success': True,
            'data': {
                'reviews': product_reviews,
                'average_rating': round(avg_rating, 1),
                'review_count': len(product_reviews)
            }
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/reviews/create', methods=['POST'])
def create_review():
    """创建评价"""
    try:
        data = request.get_json()
        
        # 验证必要字段
        required_fields = ['product_id', 'product_rating', 'merchant_rating', 'logistics_rating', 'comment']
        for field in required_fields:
            if field not in data:
                return jsonify({'success': False, 'error': f'缺少必要字段: {field}'}), 400
        
        # 获取用户信息
        username = request.headers.get('X-Username')
        if not username:
            return jsonify({'success': False, 'error': '未登录或无法识别用户'}), 401
        
        # 验证评分范围
        product_rating = int(data.get('product_rating', data.get('rating', 0)))
        merchant_rating = int(data.get('merchant_rating', 0))
        logistics_rating = int(data.get('logistics_rating', 0))
        
        if not (1 <= product_rating <= 5):
            return jsonify({'success': False, 'error': '商品评分必须在1-5之间'}), 400
        if not (1 <= merchant_rating <= 5):
            return jsonify({'success': False, 'error': '商家评分必须在1-5之间'}), 400
        if not (1 <= logistics_rating <= 5):
            return jsonify({'success': False, 'error': '物流评分必须在1-5之间'}), 400
        
        product_id = data['product_id']
        
        # 验证用户是否已购买该商品（检查订单状态是否为已送达）
        has_purchased = False
        user_orders = USER_ORDERS.get(username, [])
        
        print(f"检查用户 {username} 的订单，商品ID: {product_id}")
        print(f"用户订单数量: {len(user_orders)}")
        
        for order in user_orders:
            order_status = order.get('status')
            print(f"订单 {order.get('order_number')} 状态: {order_status}")
            
            if order_status == 'Delivered':
                items = order.get('items', [])
                print(f"订单商品数量: {len(items)}")
                
                for item in items:
                    # 检查两种可能的字段名
                    item_product_id = item.get('productId') or item.get('product_id')
                    print(f"订单商品ID: {item_product_id}, 目标商品ID: {product_id}")
                    
                    if item_product_id == product_id:
                        has_purchased = True
                        print(f"找到匹配的商品，订单号: {order.get('order_number')}")
                        break
                
                if has_purchased:
                    break
        
        if not has_purchased:
            error_msg = f'只有已购买并已送达的商品才能评价。当前商品ID: {product_id}'
            print(f"验证失败: {error_msg}")
            return jsonify({'success': False, 'error': error_msg}), 403
        
        # 检查是否已经评价过该商品
        existing_review = next((r for r in REVIEWS if r.get('product_id') == product_id and r.get('customer_id') == username), None)
        if existing_review:
            return jsonify({'success': False, 'error': '您已经评价过该商品了'}), 400
        
        # 创建评价
        review_id = f"r{int(datetime.now().timestamp())}{uuid.uuid4().hex[:6]}"
        
        # 计算平均评分（用于筛选和显示）
        avg_rating = (product_rating + merchant_rating + logistics_rating) / 3.0
        
        review = {
            'review_id': review_id,
            'product_id': product_id,
            'customer_id': username,
            'product_rating': product_rating,  # 商品满意度
            'merchant_rating': merchant_rating,  # 商家满意度
            'logistics_rating': logistics_rating,  # 物流满意度
            'rating': round(avg_rating, 1),  # 平均评分（用于显示）
            'comment': data['comment'],
            'image_urls': data.get('image_urls', []),
            'review_date': datetime.now().isoformat(),
            'is_approved': True,
            'likes': 0,
            'liked_by': [],  # 记录点赞用户ID
            'replies': [],  # 回复列表
            'merchant_reply': None  # 商家回复
        }
        
        REVIEWS.append(review)
        save_reviews(REVIEWS)
        
        print(f"评价创建成功: {review_id}")
        
        return jsonify({
            'success': True,
            'data': review
        })
        
    except Exception as e:
        print(f"创建评价时出错: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/reviews/like/<review_id>', methods=['POST'])
def like_review(review_id):
    """点赞评价"""
    try:
        review = next((r for r in REVIEWS if r.get('review_id') == review_id), None)
        if not review:
            return jsonify({'success': False, 'error': '评价不存在'}), 404
        
        review['likes'] = review.get('likes', 0) + 1
        save_reviews(REVIEWS)
        
        return jsonify({
            'success': True,
            'data': {'likes': review['likes']}
        })
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/categories', methods=['GET'])
def get_categories():
    """获取商品分类"""
    try:
        categories = [
            {'id': 'Food', 'name': '食品', 'icon': 'fas fa-utensils'},
            {'id': 'Clothing', 'name': '服装', 'icon': 'fas fa-tshirt'},
            {'id': 'Book', 'name': '图书', 'icon': 'fas fa-book'},
            {'id': 'Electronic Products', 'name': '电子产品', 'icon': 'fas fa-laptop'},
            {'id': 'Daily product', 'name': '日用品', 'icon': 'fas fa-home'}
        ]
        
        return jsonify({
            'success': True,
            'data': {
                'categories': categories
            }
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# 卖家商品管理API
@app.route('/api/seller/products', methods=['GET'])
def get_seller_products():
    """获取卖家的商品列表（从REAL_PRODUCTS中获取所有商品，卖家可以编辑描述）"""
    try:
        print(f"\n[卖家商品API] =============")
        print(f"[卖家商品API] 收到GET请求")
        print(f"[卖家商品API] 请求路径: {request.path}")
        print(f"[卖家商品API] 请求URL: {request.url}")
        
        username = request.args.get('username')
        print(f"[卖家商品API] 用户名参数: {username}")
        
        if not username:
            print("[卖家商品API] 错误: 缺少用户名参数")
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        # 返回所有商品（卖家可以编辑所有商品的描述）
        seller_products = [product.copy() for product in REAL_PRODUCTS]
        print(f"[卖家商品API] 成功返回 {len(seller_products)} 个商品")
        print(f"[卖家商品API] =============\n")
        
        return jsonify({
            'success': True,
            'data': {
                'products': seller_products,
                'total': len(seller_products)
            }
        })
        
    except Exception as e:
        print(f"[卖家商品API] 错误: {e}")
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/products', methods=['POST'])
def create_seller_product():
    """创建卖家商品"""
    try:
        data = request.get_json()
        username = data.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        # 验证必要字段
        required_fields = ['name', 'price', 'category', 'location', 'stock']
        for field in required_fields:
            if field not in data:
                return jsonify({'success': False, 'error': f'缺少必要字段: {field}'}), 400
        
        # 生成商品ID
        product_id = f"SP{int(datetime.now().timestamp())}{username[:3].upper()}"
        
        # 创建商品数据
        product_data = {
            'id': product_id,
            'name': data['name'],
            'price': float(data['price']),
            'category': data['category'],
            'location': data['location'],
            'stock': int(data['stock']),
            'description': data.get('description', f"优质{data['name']}，产地{data['location']}"),
            'image': data.get('image', f"https://via.placeholder.com/300x200?text={data['name']}"),
            'merchant_id': username,
            'created_at': datetime.now().isoformat(),
            'status': 'active'
        }
        
        # 保存商品
        if username not in SELLER_PRODUCTS:
            SELLER_PRODUCTS[username] = []
        
        SELLER_PRODUCTS[username].append(product_data)
        
        if save_seller_products(SELLER_PRODUCTS):
            return jsonify({
                'success': True,
                'data': product_data
            })
        else:
            return jsonify({'success': False, 'error': '保存商品失败'}), 500
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/products/<product_id>', methods=['PUT'])
def update_seller_product(product_id):
    """更新卖家商品"""
    try:
        data = request.get_json()
        username = data.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        if username not in SELLER_PRODUCTS:
            return jsonify({'success': False, 'error': '用户没有商品'}), 404
        
        # 查找商品
        products = SELLER_PRODUCTS[username]
        product_index = None
        for i, product in enumerate(products):
            if product['id'] == product_id:
                product_index = i
                break
        
        if product_index is None:
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        # 更新商品信息
        updated_product = products[product_index].copy()
        for key, value in data.items():
            if key not in ['username', 'id', 'created_at']:
                updated_product[key] = value
        
        updated_product['updated_at'] = datetime.now().isoformat()
        products[product_index] = updated_product
        
        if save_seller_products(SELLER_PRODUCTS):
            return jsonify({
                'success': True,
                'data': updated_product
            })
        else:
            return jsonify({'success': False, 'error': '更新商品失败'}), 500
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/products/<product_id>', methods=['DELETE'])
def delete_seller_product(product_id):
    """删除卖家商品"""
    try:
        username = request.args.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        if username not in SELLER_PRODUCTS:
            return jsonify({'success': False, 'error': '用户没有商品'}), 404
        
        # 查找并删除商品
        products = SELLER_PRODUCTS[username]
        product_index = None
        for i, product in enumerate(products):
            if product['id'] == product_id:
                product_index = i
                break
        
        if product_index is None:
            return jsonify({'success': False, 'error': '商品不存在'}), 404
        
        deleted_product = products.pop(product_index)
        
        if save_seller_products(SELLER_PRODUCTS):
            return jsonify({
                'success': True,
                'data': {'message': '商品删除成功', 'product': deleted_product}
            })
        else:
            return jsonify({'success': False, 'error': '删除商品失败'}), 500
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# 卖家店铺管理API
@app.route('/api/seller/shop', methods=['GET'])
def get_seller_shop():
    """获取卖家店铺信息"""
    try:
        username = request.args.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        if username not in SELLER_SHOPS:
            return jsonify({'success': False, 'error': '店铺不存在'}), 404
        
        shop_info = SELLER_SHOPS[username]
        return jsonify({
            'success': True,
            'data': shop_info
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/seller/shop', methods=['PUT'])
def update_seller_shop():
    """更新卖家店铺信息"""
    try:
        data = request.get_json()
        username = data.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        if username not in SELLER_SHOPS:
            return jsonify({'success': False, 'error': '店铺不存在'}), 404
        
        # 更新店铺信息
        shop_info = SELLER_SHOPS[username].copy()
        for key, value in data.items():
            if key not in ['username', 'shop_id', 'owner_username', 'created_at']:
                shop_info[key] = value
        
        shop_info['updated_at'] = datetime.now().isoformat()
        SELLER_SHOPS[username] = shop_info
        
        if save_seller_shops(SELLER_SHOPS):
            return jsonify({
                'success': True,
                'data': shop_info
            })
        else:
            return jsonify({'success': False, 'error': '更新店铺信息失败'}), 500
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

# 卖家统计API
@app.route('/api/seller/stats', methods=['GET'])
def get_seller_stats():
    """获取卖家统计数据"""
    try:
        username = request.args.get('username')
        
        if not username:
            return jsonify({'success': False, 'error': '缺少用户名参数'}), 400
        
        # 获取商品统计
        products = SELLER_PRODUCTS.get(username, [])
        total_products = len(products)
        
        # 计算总销售额（模拟数据）
        total_revenue = sum(product['price'] * product['stock'] for product in products) * 0.1
        
        # 计算平均评分
        avg_rating = 4.5 if products else 0
        
        stats = {
            'total_products': total_products,
            'total_revenue': round(total_revenue, 2),
            'avg_rating': avg_rating,
            'total_orders': 0,  # 模拟数据
            'pending_orders': 0,
            'completed_orders': 0
        }
        
        return jsonify({
            'success': True,
            'data': stats
        })
        
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@app.errorhandler(500)
def internal_error(error):
    """500错误处理"""
    return jsonify({'success': False, 'error': '服务器内部错误'}), 500

# ==================== 管理员API ====================

def check_admin_auth():
    """检查管理员权限"""
    username = request.headers.get('X-Username')
    if not username:
        return None
    
    user = USERS.get(username)
    if not user or user.get('user_type') != 'Admin':
        return None
    return username

@app.route('/api/admin/users', methods=['GET'])
def get_all_users():
    """获取所有用户列表（仅管理员）"""
    try:
        admin_username = check_admin_auth()
        if not admin_username:
            return jsonify({'success': False, 'error': '无权限访问'}), 403
        
        # 返回所有用户（密码显示为加密形式）
        users_list = []
        for username, user_data in USERS.items():
            user_info = {
                'username': user_data.get('username'),
                'user_id': user_data.get('user_id'),
                'email': user_data.get('email'),
                'phone': user_data.get('phone'),
                'user_type': user_data.get('user_type'),
                'created_at': user_data.get('created_at'),
                'password': '******' + user_data.get('password', '')[-6:] if len(user_data.get('password', '')) > 6 else '******'  # 只显示后6位
            }
            users_list.append(user_info)
        
        # 按创建时间排序
        users_list.sort(key=lambda x: x.get('created_at', ''), reverse=True)
        
        return jsonify({
            'success': True,
            'data': {
                'users': users_list,
                'total': len(users_list),
                'customers': len([u for u in users_list if u['user_type'] == 'Customer']),
                'sellers': len([u for u in users_list if u['user_type'] == 'Seller']),
                'admins': len([u for u in users_list if u['user_type'] == 'Admin'])
            }
        })
        
    except Exception as e:
        print(f"[管理员API] 获取用户列表错误: {e}")
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/admin/users/<username>', methods=['DELETE'])
def delete_user(username):
    """删除用户（仅管理员）"""
    try:
        admin_username = check_admin_auth()
        if not admin_username:
            return jsonify({'success': False, 'error': '无权限访问'}), 403
        
        # 不能删除管理员自己
        if username == admin_username:
            return jsonify({'success': False, 'error': '不能删除自己的账户'}), 400
        
        # 不能删除其他管理员
        user = USERS.get(username)
        if user and user.get('user_type') == 'Admin':
            return jsonify({'success': False, 'error': '不能删除管理员账户'}), 400
        
        if username not in USERS:
            return jsonify({'success': False, 'error': '用户不存在'}), 404
        
        # 删除用户
        deleted_user = USERS.pop(username)
        
        # 删除用户的购物车
        if username in USER_CARTS:
            USER_CARTS.pop(username)
            save_user_carts(USER_CARTS)
        
        # 删除用户的订单
        if username in USER_ORDERS:
            USER_ORDERS.pop(username)
            save_user_orders(USER_ORDERS)
        
        # 保存用户数据
        save_users(USERS)
        
        print(f"[管理员API] 管理员 {admin_username} 删除了用户 {username}")
        
        return jsonify({
            'success': True,
            'data': {
                'message': f'用户 {username} 已删除',
                'deleted_user': {
                    'username': deleted_user.get('username'),
                    'user_type': deleted_user.get('user_type')
                }
            }
        })
        
    except Exception as e:
        print(f"[管理员API] 删除用户错误: {e}")
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500

@app.route('/api/admin/daily-orders', methods=['GET'])
def get_daily_orders():
    """获取每日订单统计（仅管理员）"""
    try:
        admin_username = check_admin_auth()
        if not admin_username:
            return jsonify({'success': False, 'error': '无权限访问'}), 403
        
        # 统计每日订单
        daily_stats = {}
        total_orders = 0
        total_amount = 0
        
        for username, orders in USER_ORDERS.items():
            for order in orders:
                # 获取订单日期
                created_at = order.get('created_at', '')
                if created_at:
                    try:
                        # 解析日期
                        order_date = datetime.fromisoformat(created_at.replace('Z', '+00:00')).date() if 'T' in created_at else datetime.strptime(created_at.split()[0], '%Y-%m-%d').date()
                        date_str = order_date.strftime('%Y-%m-%d')
                    except:
                        date_str = created_at.split()[0] if ' ' in created_at else created_at[:10]
                else:
                    date_str = datetime.now().strftime('%Y-%m-%d')
                
                # 初始化日期统计
                if date_str not in daily_stats:
                    daily_stats[date_str] = {
                        'date': date_str,
                        'order_count': 0,
                        'total_amount': 0,
                        'orders': []
                    }
                
                # 累加统计
                daily_stats[date_str]['order_count'] += 1
                total_orders += 1
                
                # 计算订单金额
                order_amount = order.get('total_amount', 0) or order.get('final_amount', 0) or 0
                daily_stats[date_str]['total_amount'] += order_amount
                total_amount += order_amount
                
                # 添加订单信息（简化）
                daily_stats[date_str]['orders'].append({
                    'order_number': order.get('order_number', ''),
                    'username': username,
                    'status': order.get('status', ''),
                    'amount': order_amount,
                    'item_count': len(order.get('items', []))
                })
        
        # 转换为列表并排序
        daily_list = list(daily_stats.values())
        daily_list.sort(key=lambda x: x['date'], reverse=True)
        
        # 只返回最近30天的数据
        daily_list = daily_list[:30]
        
        print(f"[管理员API] 每日订单统计: 总计 {total_orders} 单, 金额 {total_amount:.2f}")
        
        return jsonify({
            'success': True,
            'data': {
                'daily_stats': daily_list,
                'summary': {
                    'total_orders': total_orders,
                    'total_amount': round(total_amount, 2),
                    'avg_per_order': round(total_amount / total_orders, 2) if total_orders > 0 else 0
                }
            }
        })
        
    except Exception as e:
        print(f"[管理员API] 获取每日订单统计错误: {e}")
        traceback.print_exc()
        return jsonify({'success': False, 'error': str(e)}), 500

# 静态文件路由（必须在最后，确保API路由优先匹配）
@app.route('/<path:filename>')
def static_files(filename):
    """静态文件服务"""
    # 只处理非API路径的静态文件请求
    if not filename.startswith('api'):
        try:
            return send_from_directory('.', filename)
        except Exception as e:
            print(f"静态文件服务错误: {e}")
            return jsonify({'success': False, 'error': f'文件不存在: {filename}'}), 404
    return jsonify({'success': False, 'error': '接口不存在'}), 404

if __name__ == '__main__':
    print("="*60)
    print("阿里宝宝电商平台 - Web API服务器（简化版）")
    print("="*60)
    print("正在启动服务器...")
    print("API文档:")
    print("  POST /api/auth/login - 用户登录")
    print("  POST /api/auth/register - 用户注册")
    print("  GET  /api/products - 获取商品列表")
    print("  GET  /api/products/<id> - 获取商品详情")
    print("  POST /api/products/search - 搜索商品")
    print("  GET  /api/cart - 获取购物车")
    print("  POST /api/cart/add - 添加到购物车")
    print("  GET  /api/orders - 获取订单")
    print("  POST /api/orders/create - 创建订单")
    print("  GET  /api/recommendations - 获取推荐商品")
    print("  GET  /api/categories - 获取商品分类")
    print("  GET  /api/seller/products - 获取卖家商品列表")
    print("  POST /api/seller/products - 创建卖家商品")
    print("  PUT  /api/seller/products/<id> - 更新卖家商品")
    print("  DELETE /api/seller/products/<id> - 删除卖家商品")
    print("  PUT  /api/products/<id>/description - 更新商品描述")
    print("  GET  /api/products/<id>/sales - 获取商品购买量")
    print("  GET  /api/seller/shop - 获取卖家店铺信息")
    print("  PUT  /api/seller/shop - 更新卖家店铺信息")
    print("  GET  /api/seller/stats - 获取卖家统计数据")
    print("="*60)
    print("服务器地址: http://localhost:8000")
    print("管理员账号: Mike.Chen / Chen@123")
    print("="*60)
    
    # 启动Flask服务器
    app.run(
        host='0.0.0.0',
        port=8000,
        debug=True,
        threaded=True
    )
